15. 1-D Car World Solution

Solution Exercise 1

def initialize_robot(grid_size):
    grid = [1/grid_size] * grid_size
    return grid    

Here is an alternative solution.

def initialize_robot(grid_size):

    grid = []

    for i in range(grid_size):
        grid.append(1/grid_size)

    return grid

Solution Exercise 2

def grid_probability(grid, position):

    if position < len(grid):
        return grid[position]

    return None

You could also check to make sure that the position variable is non-negative. But in Python, negative list indices are actually legitimate. grid[-1] gives you access to the last element in the list. grid[-2] gives you access to the second to last element, etc.

Solution Exercise 3

import matplotlib.pyplot as plt
import numpy as np

def output_map(grid):

    x_labels = range(len(grid))

    plt.bar(x_labels, grid)
    plt.xlabel('Grid Space')
    plt.ylabel('Probability')
    plt.title('Probability of the Robot Being at Each Space on the Grid')
    plt.show()

Solution Exercise 4

def update_probabilities(grid, updates):  

    for i in range(len(updates)):
        grid[updates[i][0]] = updates[i][1]

    return grid

Here is an alternative solution.

def update_probabilities(grid, updates):
    for update in updates:
        grid[update[0]] = update[1] 
    return grid